1
|
|
|
class Lightbox { |
2
|
|
|
constructor(options) { |
3
|
|
|
this.targets = typeof options.targets === 'string' ? document.querySelectorAll(options.targets) : options.targets; |
4
|
|
|
this.initClasses(); |
5
|
|
|
this.initClone(); |
6
|
|
|
this.initClose(); |
7
|
|
|
} |
8
|
|
|
|
9
|
|
|
initClasses() { |
10
|
|
|
this.targets.forEach(function (target) { |
11
|
|
|
target.classList.add('lightbox'); |
12
|
|
|
}); |
13
|
|
|
} |
14
|
|
|
|
15
|
|
|
initHTML(target, position) { |
16
|
|
|
let wrapper = document.createElement('div'); |
17
|
|
|
wrapper.classList.add('clone-bg'); |
18
|
|
|
|
19
|
|
|
setTimeout(() => { |
20
|
|
|
wrapper.classList.add('active'); |
21
|
|
|
}, 100); |
22
|
|
|
|
23
|
|
|
let clone = document.createElement('div'); |
24
|
|
|
clone.classList.add('clone'); |
25
|
|
|
clone.style.top = position.top + 'px'; |
26
|
|
|
clone.style.left = position.left + 'px'; |
27
|
|
|
clone.style.width = target.naturalWidth + 'px'; |
28
|
|
|
clone.style.height = target.naturalHeight + 'px'; |
29
|
|
|
|
30
|
|
|
setTimeout(() => { |
31
|
|
|
clone.classList.add('centered'); |
32
|
|
|
}, 100); |
33
|
|
|
|
34
|
|
|
let cloneImg = document.createElement('img'); |
35
|
|
|
cloneImg.src = target.src; |
36
|
|
|
|
37
|
|
|
clone.appendChild(cloneImg); |
38
|
|
|
wrapper.appendChild(clone); |
39
|
|
|
document.body.appendChild(wrapper); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
initClone() { |
43
|
|
|
let that = this; |
44
|
|
|
this.targets.forEach(function (target) { |
45
|
|
|
target.addEventListener('click', function (e) { |
46
|
|
|
that.initHTML(e.target, that.getTargetPosition(target)); |
47
|
|
|
}) |
48
|
|
|
}); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
getTargetPosition(target) { |
52
|
|
|
let targetPosition = target.getBoundingClientRect(); |
53
|
|
|
|
54
|
|
|
return { |
55
|
|
|
top: targetPosition.top, |
56
|
|
|
left: targetPosition.left |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
initClose() { |
61
|
|
|
this.bodyClose(); |
62
|
|
|
this.scrollClose(); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
static close() { |
66
|
|
|
let parent = document.querySelector('.clone-bg'); |
67
|
|
|
let child = parent.querySelector('.clone'); |
68
|
|
|
child.classList.remove('centered'); |
69
|
|
|
|
70
|
|
|
setTimeout(() => { |
71
|
|
|
parent.remove(); |
72
|
|
|
}, 500); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
bodyClose() { |
76
|
|
|
let that = this; |
|
|
|
|
77
|
|
|
|
78
|
|
|
document.addEventListener('click', function (e) { |
79
|
|
|
e.preventDefault(); |
80
|
|
|
|
81
|
|
|
if(e.target.closest('.clone-bg')) { |
82
|
|
|
Lightbox.close(); |
83
|
|
|
} |
84
|
|
|
}); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
scrollClose() { |
88
|
|
|
let that = this; |
|
|
|
|
89
|
|
|
|
90
|
|
|
document.addEventListener('scroll', function () { |
91
|
|
|
Lightbox.close(); |
92
|
|
|
}); |
93
|
|
|
} |
94
|
|
|
} |